package com.dszq.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.dszq.behavior.service.ApReadBehaviorService;
import com.dszq.common.constants.BehaviorConstants;
import com.dszq.common.constants.HotArticleConstants;
import com.dszq.common.redis.CacheService;
import com.dszq.model.behavior.dtos.ReadBehaviorDto;
import com.dszq.model.common.dtos.ResponseResult;
import com.dszq.model.common.enums.AppHttpCodeEnum;
import com.dszq.model.mess.UpdateArticleMess;
import com.dszq.model.user.pojos.ApUser;
import com.dszq.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

/**
 * [一句话描述该类的功能]
 *
 * @author : [Lenovo]
 * @version : [v1.0]
 * @createTime : [2024/5/2 16:39]
 */
@Service
@Slf4j
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {
    @Autowired
    private CacheService cacheService;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    /**
     * 保存阅读行为
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        //1.检查参数
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        String  readBehaviorJson = (String)cacheService.hGet(BehaviorConstants.READ_BEHAVIOR + dto.getArticleId(), user.getId().toString());
        if (StringUtils.isNotBlank(readBehaviorJson))
        {
            ReadBehaviorDto readBehaviorDto = JSON.parseObject(readBehaviorJson,ReadBehaviorDto.class);
            dto.setCount((short) (readBehaviorDto.getCount()+dto.getCount()));
        }
        // 保存当前key
        log.info("保存当前key:{} {} {}", dto.getArticleId(), user.getId(), dto);
        cacheService.hPut(BehaviorConstants.READ_BEHAVIOR+dto.getArticleId(),user.getId().toString(),dto.toString());
        UpdateArticleMess updateArticleMess = new UpdateArticleMess();
        updateArticleMess.setArticleId(dto.getArticleId());
        updateArticleMess.setType(UpdateArticleMess.UpdateArticleType.VIEWS);
        updateArticleMess.setAdd(1);
        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC,JSON.toJSONString(updateArticleMess));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
